package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

type Login struct {
	User string `form:"user" json:"user" xml:"user" binding:"required"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

func main() {
	router := gin.Default()

	router.POST("/loginJSON", BindJson)
	router.POST("/loginXML", BindXml)
	router.POST("/loginForm", bindForm)

	router.Run()
}


func BindJson(c *gin.Context){
	var json Login

	err := c.ShouldBindJSON(&json)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error" : err.Error(),
		})
		return
	}

	if json.User != "admin" || json.Password != "123" {
		c.JSON(http.StatusUnauthorized, gin.H{
			"status" :  "unauthorized",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"status" : "logined in",
	})
}

/*
<?xml version="1.0" encoding="UTF-8"?>
<root>
    <user>user</user>
    <password>123</password>
</root>
 */
func BindXml(c *gin.Context)  {
	var xml Login
	if err := c.ShouldBindXML(&xml); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if xml.User != "manu" || xml.Password != "123" {
		c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
}

func bindForm(c *gin.Context) {
	var form Login
	if err := c.ShouldBind(&form); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	if form.User != "manu" || form.Password != "123" {
		c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
}